package com.ias.agdis_r.manager;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

import org.xmlpull.v1.XmlPullParser;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
//import android.support.v4.app.FragmentActivity;
import androidx.fragment.app.FragmentActivity;
import android.util.Log;
import android.util.Xml;

import com.ias.agdis_r.bean.message.SummaryTemplates;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.util.sdcard.SDcard;

/**
 * 数据库管理类
 * 
 * @author zhangsc
 * 
 */
public class DataBaseManager {
	private static DataBaseManager instance = null;// 单例的数据库管理器
	private Context context;
	private Handler UIHandler = null;
	public static String PHOTO_FORDER_PATH = SDcard.getSDPATH()+"/IASDataBase/image/";
	public static String DCIM_FORDER_PATH = SDcard.getSDPATH()+"/IASDataBase/dcim/";
	private FragmentActivity boxActivity=null;
	private FragmentActivity taskInfoActivity=null;
	private FragmentActivity nfTaskInfoActivity=null;

	public Handler getUIHandler() {
		return UIHandler;
	}

	public void setUIHandler(Handler UIHandler) {
		this.UIHandler = UIHandler;
	}

	public DataBaseManager(Context context) {
		this.context = context;
		instance = this;
	}

	public void setTaskInfoActivity(FragmentActivity taskInfoActivity){
		this.taskInfoActivity = taskInfoActivity;
	}

	public void removeTaskInfoActivity(){

		if(this.taskInfoActivity!=null)
		{
			this.taskInfoActivity.finish();
		}
	}

	public void setNfTaskInfoActivity(FragmentActivity nfTaskInfoActivity) {
		this.nfTaskInfoActivity = nfTaskInfoActivity;
	}

	public void removeNFTaskInfoActivity(){

		if(this.nfTaskInfoActivity!=null)
		{
			this.nfTaskInfoActivity.finish();
		}
	}

	public void setBoxActivty(FragmentActivity boxActivity){
		this.boxActivity = boxActivity;
	}

	public FragmentActivity getBoxActivty(){
		return this.boxActivity;
	}
	
	public void removeBoxActivty(){
		
		if(this.boxActivity!=null)
		{
			this.boxActivity.finish();
		}
	}

	/**
	 * 根据表名获取表
	 * 
	 * @param tableName
	 *            表名
	 * @return SharedPreferences
	 */
	public SharedPreferences getTable(String tableName) {
		return context.getSharedPreferences(tableName, 0);
	}

	/**
	 * 插入到数据库
	 * 
	 * @param tableName
	 * @param colName
	 * @param value
	 */
	public boolean insert(String tableName, String colName, String value) {
		return XmlManager.getInstance().inert(tableName, colName, value);
	}

	public void insertShared(String tableName, String colName, String value) {
		SharedPreferences.Editor editor = getTable(tableName).edit();
		editor.putString(colName, value);
		editor.commit();
	}

	public void insertShared(String tableName, String colName, int value) {
		SharedPreferences.Editor editor = getTable(tableName).edit();
		editor.putInt(colName, value);
		editor.commit();
	}

	/**
	 * 插入到数据库
	 * 
	 * @param tableName
	 * @param colName
	 * @param value
	 */
	public void insert(String tableName, String colName, boolean value) {
		if (value == true) {
			XmlManager.getInstance().inert(tableName, colName, "1");
		} else {
			XmlManager.getInstance().inert(tableName, colName, "0");
		}

	}

	/**
	 * 插入到数据库
	 * 
	 * @param tableName
	 * @param colName
	 * @param value
	 */
	public boolean insert(String tableName, String colName, int value) {
		return XmlManager.getInstance().inert(tableName, colName, value + "");

	}

	/**
	 * 插入到数据库
	 * 
	 * @param packageName
	 * @param tableName
	 * @param colName
	 * @param value
	 */

	public boolean insert(String packageName, String tableName, String colName,
			int value) {

		return XmlManager.getInstance().inert(packageName, tableName, colName,
				value + "");
	}

	public boolean insert(String packageName, String tableName, String colName,
			String value) {

		return XmlManager.getInstance().inert(packageName, tableName, colName,
				value);
	}

	/**
	 * 获取数据库表中String字段内容
	 * 
	 * @param tableName
	 *            表名
	 * @param colName
	 *            字段名
	 * @return 字段的值
	 */
	public String getString(String tableName, String colName) {

		if (S.isNotEmpty(tableName) && S.isNotEmpty(colName)) {
			String a = XmlManager.getInstance().select(tableName, colName);
			return a;
		}
		return "";
	}

	/**
	 * 获取数据库表中String字段内容
	 * 
	 * @param 配置文件包
	 * 
	 * @param tableName
	 *            表名
	 * @param colName
	 *            字段名
	 * @return 字段的值
	 */
	public String getString(String packageName, String tableName, String colName) {

		if (S.isNotEmpty(packageName) && S.isNotEmpty(tableName)
				&& S.isNotEmpty(colName)) {
			return XmlManager.getInstance().select(packageName, tableName,
					colName);
		}
		return "";
	}

	/**
	 * 获取数据库表中int字段内容
	 * 
	 * @param 配置文件包
	 * 
	 * @param tableName
	 *            表名
	 * @param colName
	 *            字段名
	 * @return 字段的值
	 */
	public int getInt(String packageName, String tableName, String colName) {

		int result = 0;
		if (S.isNotEmpty(packageName) && S.isNotEmpty(tableName)
				&& S.isNotEmpty(colName)) {
			try {

				result = Integer.parseInt(XmlManager.getInstance().select(
						packageName, tableName, colName));

			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 获取SD卡中的图片
	 * 
	 * @param imageName
	 *            图片名称
	 * @return 该图片的BitMap
	 */
	public Drawable getImage(String imageName) {
		String SDPATH = SDcard.getSDPATH();
		Log.i("tag", "SDPATH:" + SDPATH);
		if (SDPATH.equals("")) {
			return null;
		}
		try {
			String imagePath = SDPATH + "/" + "IASDataBase" + "/" + imageName;
			Log.i("tag", "imagePath:" + imagePath);
			Bitmap bm = BitmapFactory.decodeFile(imagePath);
			if (bm == null) {
				return null;
			}
			Drawable drawable = new BitmapDrawable(bm);
			return drawable;

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	public int isDataBaseExist(){
		int code = -1;
		String SDPATH = SDcard.getSDPATH();
		if (S.isEmpty(SDPATH)){
			// SD卡未挂载由XmlManager.SDRemindThread处理
			return 0;
		}
		File file = new File(SDPATH + "/IASDataBase/");
		if (file.exists()){
			return 1;
		}else {
			// 未检测到配置文件
			return -1;
		}
	}

	/**
	 * 
	 * @param path
	 * @return
	 */
	public File[] getVersionUpdateFiles(String path) {
		String SDPATH = SDcard.getSDPATH();
		if (SDPATH.equals("")) {
			return null;
		}
		try {
			String imagePath = SDPATH + "/" + path;
			File forder = new File(imagePath).getAbsoluteFile();
			File[] fileList = forder.listFiles(); /* 此处获取文件夹下的所有文件 */
			return fileList;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	public String getSharedString(String tableName, String colName) {
		return getValueWithDefaut(tableName, colName, "");
	}

	public int getSharedInt(String tableName, String colName) {
		return getValueWithDefaut(tableName, colName, 0);
	}

	public boolean getBoolean(String tableName, String colName) {

		if (S.isNotEmpty(tableName) && S.isNotEmpty(colName)) {
			String colString = XmlManager.getInstance().select(tableName,
					colName);
			if ("1".equals(colString)) {
				return true;
			}
		}
		return false;
	}

	public int getInt(String tableName, String colName) {

		if (S.isNotEmpty(tableName) && S.isNotEmpty(colName)) {

			String colString = XmlManager.getInstance().select(tableName,
					colName);
			if (S.isNotEmpty(colString)) {
				try {
					return Integer.parseInt(colString);
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return 0;
				}
			}
		}
		return 0;
	}

	public long getLong(String tableName, String colName) {

		if (S.isNotEmpty(tableName) && S.isNotEmpty(colName)) {

			String colString = XmlManager.getInstance().select(tableName,
					colName);
			if (S.isNotEmpty(colString)) {
				try {
					return Long.parseLong(colString);
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return 0;
				}
			}
		}
		return 0;
	}

	public double getDouble(String tableName, String colName) {

		if (S.isNotEmpty(tableName) && S.isNotEmpty(colName)) {

			String colString = XmlManager.getInstance().select(tableName,
					colName);
			if (S.isNotEmpty(colString)) {
				try {
					return Double.parseDouble(colString);
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return 0;
				}
			}
		}
		return 0;
	}

	// public int getInt(String tableName, String colName) {
	// if (S.isNotEmpty(tableName) && S.isNotEmpty(colName)) {
	// return getTable(tableName).getInt(colName, 0);
	// }
	// return 0;
	// }

	/**
	 * 获取数据库表中String字段内容
	 * 
	 * @param tableName
	 *            表名
	 * @param colName
	 *            字段名
	 * @param defaultValue
	 *            默认的返回值
	 * @return 字段的值
	 */
	public String getValueWithDefaut(String tableName, String colName,
			String defaultValue) {
		String result = "";
		if (S.isNotEmpty(tableName) && S.isNotEmpty(colName)) {
			result = getTable(tableName).getString(colName, defaultValue);
		}
		return result;
	}

	/**
	 * 获取数据库表中Int字段内容
	 * 
	 * @param tableName
	 *            表名
	 * @param colName
	 *            字段名
	 * @param defaultValue
	 *            默认的返回值
	 * @return 字段的值
	 */
	public int getValueWithDefaut(String tableName, String colName,
			int defaultValue) {
		int result = 0;
		if (S.isNotEmpty(tableName) && S.isNotEmpty(colName)) {
			result = getTable(tableName).getInt(colName, defaultValue);
		}
		return result;
	}

	/**
	 * 单例模式
	 * 
	 * @return
	 */
	public static DataBaseManager getInstance() {
		// TODO Auto-generated method stub
		return instance;
	}

	public void delete(String tableName) {
		getTable(tableName).edit().clear().commit();
	}

	public Context getContext() {
		return context;
	}

	/**
	 * 保存采集数据信息
	 */
	public void saveConfigTxt(String editkey, String editvalue) {
		FileInputStream fis = null;
		FileOutputStream fos = null;
		Properties pold = new Properties();
		Properties pnew = new Properties();
		try {
			PrintStream ps = null;
			fis = DataBaseManager.getInstance().getContext()
					.openFileInput("config.txt");
			pold.load(fis);
			fis.close();
			fos = DataBaseManager.getInstance().getContext()
					.openFileOutput("config.txt", Context.MODE_PRIVATE);
			ps = new PrintStream(fos);
			Enumeration en = pold.propertyNames();
			while (en.hasMoreElements()) {
				String key = (String) en.nextElement();
				if (key.equals(editkey)) {
					continue;
				} else {
					String value = pold.getProperty(key);
					pnew.put(key, value);
				}
			}
			pnew.put(editkey, editvalue);
			pnew.list(ps);

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 读取航班总结短语
	 */
	public SummaryTemplates readSummaryMsg() {
		SummaryTemplates summaryTemplate = new SummaryTemplates();
		String SDPATH = SDcard.getSDPATH();
		if (SDPATH.equals("")) {
			return summaryTemplate;
		}
		FileInputStream fis = null;
		InputStream is = null;
		try {
			String summaryPath = SDPATH + "/" + "IASDataBase" + "/" + "templet"
					+ "/" + "TEMPLET_SUMMARY.xml";
			fis = new FileInputStream(new File(summaryPath));
			is = new BufferedInputStream(fis);
			XmlPullParser parser = Xml.newPullParser();
			parser.setInput(is, "utf-8");// 设置解析的数据源
			int type = parser.getEventType();
			List<String> summaryList = null;
			String pid = "";
			while (type != XmlPullParser.END_DOCUMENT) {
				switch (type) {
				case XmlPullParser.START_DOCUMENT:// 判断当前事件是否是文档开始事件
					break;
				case XmlPullParser.START_TAG:
					if ("NODE".equals(parser.getName())) {
						summaryList = new ArrayList<String>();
						pid = parser.getAttributeValue(0);
					} else if ("ITEM".equals(parser.getName())) {
						summaryList.add(parser.nextText());
					}
					break;
				case XmlPullParser.END_TAG:
					if ("NODE".equals(parser.getName())) {
						summaryTemplate.put(pid, summaryList);
						summaryList = null;
						pid = "";
					}
					break;
				}
				type = parser.next();
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return summaryTemplate;
	}
}
